Quindi sto sviluppando un gioco sociale, in cui hai una certa quantità di tempo per svolgere un compito. Dato che è social, puoi chattare con l'altro giocatore. Ogni volta che ricevi un messaggio di chat riceverai anche una notifica e facendo clic su di esso verrai reindirizzato alla schermata della chat con lui. In questo momento funziona bene. Quello che non voglio è che l'utente riceva una notifica chat mentre sta effettivamente giocando su PlayActivity. Sarebbe anche un bene, se la notifica già mostrata potesse essere ignorata o sospesa in un secondo momento mentre si trova su PlayActivity. È realizzabile? Un approccio diverso potrebbe essere quello di annullare tutte le notifiche già visualizzate e mettere il BroadcastReceiver in sospensione e riattivare tutte le notifiche e il BroadcastReceiver dopo che PlayActivity è terminato? Neanche possibile? L'app potrebbe almeno chiedere prima di lasciare l'attività? in questo modo potrei avvertirlo e se se ne va, il gioco potrebbe essere valutato contro di lui. Quello che faccio adesso è solo una soluzione alternativa, creo la PlayActivity a schermo intero e controllo se lo stato attivo è cambiato, ad es. se sta trascinando verso il basso la barra di stato / area di notifica. Ma questo è solo un trucco, qualcosa che mi piacerebbe davvero eliminarlo. Come vedi, non sono davvero sicuro di quale potrebbe essere l'approccio giusto qui. Cosa farebbe uno sviluppatore di software Android professionista nel mio caso? Grazie in anticipo! In questo momento sto gestendo le notifiche estendendo un BroadcastReceiver. Il codice è aggiunto alla fine, se hai bisogno di altre parti del mio codice, fammelo sapere! Public class PushBroadcastReceiver estende BroadcastReceiver { @Oltrepassare public void onReceive (Context context, Intent intent) { provare { JSONObject json = nuovo JSONObject ( intent.getExtras () .getString ("KEY")); notifica (contesto, intento, json); } catch (JSONException e) { L.debug (App.TAG, "JSONException:" + e.getMessage ()); } } private void notify (Context ctx, Intent i, JSONObject dataObject) genera JSONException { NotificationManager nm = (NotificationManager) ctx.getSystemService (Context.NOTIFICATION_SERVICE); boolean createNotification = false; PendingIntent pi = null; int gameId = 0; // Chiacchierare if (dataObject.getString ("KEY_CHAT"). è uguale a ("VALUE_CHAT")) { Intento intento = nuovo intento (ctx, ChatActivity.class); intent.putExtra ("opponenteUsername", dataObject.getString (PARSE_JSON_OPPONENT_USERNAME_KEY)); intent.putExtra ("gameId", dataObject.getString (PARSE_JSON_GAME_ID_KEY)); pi = PendingIntent.getActivity (ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); gameId = Integer.parseInt (dataObject.getString (PARSE_JSON_GAME_ID_KEY)); createNotification = true; // gioco } altrimenti se (dataObject.getString ("KEY_GAME"). è uguale a ("VALUE_GAME")) { Intent intent = nuovo intento (ctx, SS6RunningGameActivity.class); intent.putExtra ("gameId", dataObject.getString (PARSE_JSON_GAME_ID_KEY)); gameId = Integer.parseInt (dataObject.getString (PARSE_JSON_GAME_ID_KEY)); pi = PendingIntent.getActivity (ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); createNotification = true; } if (createNotification) { Suono Uri = Uri.parse ("android.resource: //" + ctx.getPackageName () + "/" + R.raw.push_notif); int icon = R.drawable.icon_notification_android; String tickerText = dataObject.getString ("TEXT"); Notifica mNotification = new NotificationCompat.Builder (ctx) .setContentTitle (ctx.getResources (). getString (R.string.app_name)) .setContentText (tickerText) .setSmallIcon (icona) .setContentIntent (pi) .setSound (suono) .setDefaults (Notification.DEFAULT_VIBRATE) .setAutoCancel (true) .setStyle (new NotificationCompat.BigTextStyle () .bigText (tickerText)) .costruire(); nm.notify (gameId, mNotification); } }
2021-02-05 08:16:21
Ci possono essere molti approcci a questo. Uno dei più semplici sarebbe il seguente: Usa SharedPreferences. Aggiungi un valore booleano per indicare che PlayActivity è attualmente in esecuzione. In onCreate (Bundle) di PlayActivity, procedi come segue: // Inizializzazione Preferenze SharedPreferences = getSharedPreferences ("MY_PREF_FILE_NAME", 0); Modifica modifica = preferenze.edit (); // Qui, "PLAY_ACTIVITY_IS_RUNNING" è la "chiave" e "true" è il valore // Stiamo dicendo che "PlayActivity" è in esecuzione edit.putBoolean ("PLAY_ACTIVITY_IS_RUNNING", true); edit.commit (); Ora, in onPause () di PlayActivity, imposta questo valore booleano su false, indicando che stiamo per lasciare PlayActivity: // Inizializzazione Preferenze SharedPreferences = getSharedPreferences ("MY_PREF_FILE_NAME", 0); Modifica modifica = preferenze.edit (); // Qui, "PLAY_ACTIVITY_IS_RUNNING" è la "chiave" e "false" è il valore // Stiamo dicendo che "PlayActivity" non è più in esecuzione edit.putBoolean ("PLAY_ACTIVITY_IS_RUNNING", false); edit.commit (); Il riposo è abbastanza semplice. In PushBroadcastReceiver, apri SharedPreferences e verifica il valore assegnato alla chiave PLAY_ACTIVITY_IS_RUNNING. Se questo valore è falso, continua a pubblicare le notifiche. Altrimenti, raccoglili per dopo. Public class PushBroadcastReceiver estende BroadcastReceiver { @Oltrepassare public void onReceive (Context context, Intent intent) { Preferenze SharedPreferences = context.getSharedPreferences ( "MY_PREF_FILE_NAME", 0); // Recupera il valore memorizzato per la chiave "PLAY_ACTIVITY_IS_RUNNING" // Il secondo argomento "false" è il valore predefinito // nel caso in cui la chiave non esiste - questo è logicamente corretto boolean playActivityIsRunning = Preferences.getBoolean ( "PLAY_ACTIVITY_IS_RUNNING", false) // PlayActivity è in esecuzione if (playActivityIsRunning) { // archivia gli oggetti JSON da qualche parte e gestiscili in seguito } altro { provare { JSONObject json = nuovo JSONObject (intent.getExtras (). GetString ("KEY")); notifica (contesto, intento, json); } catch (JSONException e) { L.debug (App.TAG, "JSONException:" + e.getMessage ()); } } } private void notify (Context ctx, Intent i, JSONObject dataObject) genera JSONException { .... .... } } Dovrai trovare un modo per pubblicare le notifiche in sospeso. Una soluzione è inviare una trasmissione separata a un altro BroadcastReceiver in onPause () di PlayActivity. Ma questo potrebbe essere problematico perché onPause () viene chiamato anche quando l'utente sta cambiando orientamento. Forse questo BroadcastReceiver può iniziare a funzionare dopo un secondo di ritardo? Questo sarebbe tempo sufficiente per ricreare l'attività e il valore di PLAY_ACTIVITY_IS_RUNNING reimpostato (poiché onCreate (Bundle) di PlayActivity verrà richiamato di nuovo). Quindi, il flusso sarebbe: viene chiamato onPause impostare il valore su false in SharedPreferences inviare la trasmissione per gestire le notifiche in sospeso inserire il codice di BroadcastReceiver all'interno di un Runnable. Pubblica questo eseguibile con un ritardo di 1 secondo utilizzando un gestore. all'interno di BroadcastReciever => controlla il valore di PLAY_ACTIVITY_IS_RUNNING in SharedPreferences <= questo sarà fatto dopo 1 secondo. Se l'utente ha cambiato solo l'orientamento dello schermo, il valore di PLAY_ACTIVITY_IS_RUNNING sarebbe vero. In caso contrario, se l'utente viene allontanato da PlayActivity, il valore sarebbe falso. 7 | la tua risposta StackExchange.ifUsing ("editor", function () { StackExchange.using ("externalEditor", function () { StackExchange.using ("snippets", function () { StackExchange.snippets.init (); }); }); }, "frammenti di codice"); StackExchange.ready (function () { var channelOptions = { tag: "" .split (""), id: "1" }; initTagRenderer ("". split (""), "" .split (""), channelOptions); StackExchange.using ("externalEditor", function () { // Devo attivare l'editor dopo gli snippet, se gli snippet sono abilitati if (StackExchange.settings.snippets.snippetsEnabled) { StackExchange.using ("snippets", function () { createEditor (); }); } altro { createEditor (); } }); function createEditor () { StackExchange.prepareEditor ({ useStacksEditor: false, heartbeatType: 'answer', autoActivateHeartbeat: false, convertImagesToLinks: true, noModals: true, showLowRepImageUploadWarning: true, reputationToPostImages: 10, bindNavPrevention: true, suffisso: "", imageUploader: { brandingHtml: "Powered by \ u003ca href = \" https: //imgur.com/ \ "\ u003e \ u003csvg class = \" svg-icon \ "width = \" 50 \ "height = \" 18 \ "viewBox = \ "0 0 50 18 \" fill = \ "none \" xmlns = \ "http: //www.w3.org/2000/svg \" \ u003e \ u003cpath d = \ "M46.1709 9.17788C46.1709 8.26454 46.2665 7.94324 47.1084 7.58816C47.4091 7.46349 47.7169 7.36433 48.0099 7.26993C48.9099 6.97997 49.672 6.73443 49.672 5.93063C49.672 5.22043 48.9832 4.61182 48.1414 4.61182C47.4335 4.62993C48.9099 6.97997 49.672 6.73443 49.672 5.93063C49.672 5.22043 48.9832 4.61182 48.1414 4.61182C47.4335 4.62481 46.72543 4.9162889 464562 46.72543 4.9162889 4.645.2543 4.6531 4.69562 4.65.695.65.69562 C4562 4.6531.495.65.69562 C4562.65.695.6531.495.69562 C4562. 43.1481 6.59048V11.9512C43.1481 13.2535 43.6264 13.8962 44.6595 13.8962C45.6924 13.8962 46.1709 13.2535 46.1709 11.9512V9.17788Z \ "/ \ u003e \ u003cpath d = \" M32.492 10.1419C324.192 12.69537.0451 14.0484C39.9723 14.0484 41.5985 12.6954 41.5985 10.1419V6.59049C41.5985 5.28821 41.1394 4.66232 40.1061 4.66232C39.0732 4.66232 38.5948 5.28821 38.5948 6.59049V9.60062C38.5948 10.8451.55.495.595.635.495.495.6 4954 5.28821 35.0173 4.66232 34.0034 4.66232C32.9703 4.66232 32.492 5.28821 32.492 6.59049V10.1419Z \ "/ \ u003e \ u003cpath fill-rule = \" evenodd \ "clip-rule = \" evenodd \ "d = \" M25.6622 17.6335 C27.8049 17.6335 29.3739 16.9402 30.2537 15.6379C30.8468 14.7755 30.9615 13.5579 30.9615 11.9512V6.59049 C30.9615 5.28821 30.4833 4.66231 29.4502 4.66231C28.9913 4.66231 28.4555 4.94978 28.1109 4.5960.709.532.709 4.536.79 C21.0134 11.9852 23.003 13.913 25.3754 13.913C26.5612 13.913 27.4607 13.4902 28.1109 12.6616C28.1109 12.7229 28.1161 12.7799 28.121 12.8346C28.1256 12.8854 28.1301 12.9342 28.1301 12.6616C28.1109 12.7229 28.1161 12.7799 28.121 12.8346C28.1256 12.8854 28.1301 12.934.7 28.1301 12.983.432 15321 C37 15321.2301.230 349 15.2321 24.1352 14.9821 23.5661 14.7787C23.176 14.6393 22.8472 14.5218 22.5437 14.5218C21.7977 14.5218 21.2429 15.0123 21.2429 15.6887C21.2429 16.7375 22.904772 17.6335 25.6622 17.6335.9972 17.6335 25.6622 17.6335.99 7,928 24,0924 7,943,0943 7,924 C28.0918 10.6321 27.2311 11.5116 26.1024 11.5116C24.9737 11.5116 24.1317 10.6491 24.1317 9.27932Z \ "/ \ u003e \ u003cpath d = \" M16.8045 11.9512C16.8045 13.2535 17.2637 13.8962 18.2980 13.89.25. 12928C19.8079 5.82936 18.4879 4.62866 16.4027 4.62866C15.1594 4.62866 14.279 4.98375 13.3609 5.88013C12.653 5.05154 11.6581 4.62866 10.3573 4.62866C9.34336 4.62866 8.57809 4.89931 7.9466 5.5079C7.583.1066 5.5079 9512C5.00066 13.2535 5.47873 13.8962 6.51203 13.8962C7.54479 13.8962 8.0232 13.2535 8.0232 11.9512V8.90741C8.0232 7.58817 8.44431 6.91179 9.53458 6.91179C10.5104 6.91179 10. 893 7.58817 10.893 8.94108V11.9512C10.893 13.2535 11.3711 13.8962 12.4044 13.8962C13.4375 13.8962 13.9157 13.2535 13.9157 11.9512V8.90741C13.9157 7.58817 14.3365 6.91179 15.4269 6.91179pathC16.4027 8.9410.95 16.91179Percorso 80: 4511. d = \ "M3.31675 6.59049C3.31675 5.28821 2.83866 4.66232 1.82471 4.66232C0.791758 4.66232 0.313354 5.28821 0.313354 6.59049V11.9512C0.313354 13.2535 0.791758 13.8962 1.82471 13.8962C3.85798 13.8962 3.31675 u005 \ u003cpath d = \ "M1.87209 0.400291C0.843612 0.400291 0 1.1159 0 1.98861C0 2.87869 0.822846 3.57676 1.87209 3.57676C2.90056 3.57676 3.7234 2.87869 3.7234 1.98861C3.7234 1.1159 2.90056 0.400 \\ "/ \ u003e \ u003c / svg \ u003e \ u003c / a \ u003e", contentPolicyHtml: "Contributi degli utenti con licenza \ u003ca href = \" https: //stackoverflow.com/help/licensing \ "\ u003ecc by-sa \ u003c / a \ u003e \ u003ca href = \" https://stackoverflow.com / legal / content-policy \ "\ u003e (content policy) \ u003c / a \ u003e", allowUrls: true }, onDemand: true, discardSelector: ".discard-answer" , immediatamenteShowMarkdownHelp: true, enableTables: true, enableSnippets: true }); } }); Grazie per aver contribuito con una risposta a Stack Overflow! Assicurati di rispondere alla domanda. Fornisci dettagli e condividi la tua ricerca! Ma evita ... Chiedere aiuto, chiarimenti o rispondere ad altre risposte. Fare dichiarazioni basate su opinioni; supportali con riferimenti o esperienza personale. Per saperne di più, consulta i nostri suggerimenti su come scrivere ottime risposte. Bozza salvata Bozza scartata Registrati o fai il login StackExchange.ready (function () { StackExchange.helpers.onClickDraftSave ('# login-link'); }); Registrati utilizzando Google Iscriviti utilizzando Facebook Iscriviti utilizzando e-mail e password Invia Pubblica come ospite Nome E-mail Obbligatorio, ma mai mostrato StackExchange.ready ( funzione () { StackExchange.openid.initPostLogin ('. New-post-login', 'https% 3a% 2f% 2fstackoverflow.com% 2fquestions% 2f25114521% 2fis-it-possible-to-suspend-già-mostrato-e-nuove-notifiche- for-an-amount-of% 23new-answer ',' question_page '); } ); Pubblica come ospite Nome E-mail Obbligatorio, ma mai mostrato Pubblica la tua risposta Scartare Facendo clic su "Pubblica la tua risposta", accetti i nostri termini di servizio, politica sulla privacy e politica sui cookie Non è la risposta che stai cercando? Sfoglia altre domande contrassegnate con notifiche Android push o fai la tua domanda.